package au.com.mason.propertyTracker.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import au.com.mason.propertyTracker.domain.Suburb;

@Repository
public class SuburbDAO extends HibernateDaoSupport {

	public SuburbDAO() {}
	
	public Object findById(int id) {
		return getHibernateTemplate().get(Suburb.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List findAll() {
        DetachedCriteria criteria = getCriteria();

        return getHibernateTemplate().findByCriteria(criteria);
    }

	protected DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(Suburb.class);
	}
	
	public Serializable save(Object object) {
		if (object.getClass().getName().startsWith(Suburb.class.getName())) {
			return getHibernateTemplate().save(object);
		}
		
		throw new IllegalArgumentException("expect object of type " + Suburb.class);
	}
	
	public void update(Object object) {
		if (object.getClass().getName().startsWith(Suburb.class.getName())) {
			getHibernateTemplate().update(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + Suburb.class);
		}
	}
	
	public void delete(Object object) {
		if (object.getClass().getName().startsWith(Suburb.class.getName())) {
			getHibernateTemplate().delete(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + Suburb.class);
		}
	}
	
	public List<Suburb> getSuburbs() {
	 	String sql = "from Suburb order by name";
       	Query query = getSession().createQuery(sql);
       	
       	return query.list();
	}	
	
	public Suburb getSuburb(String suburb) {
		
	 	String sql = "from Suburb where name = :name";
       	Query query = getSession().createQuery(sql);
       	query.setParameter("name", suburb);
       	
       	return (Suburb) query.uniqueResult();
	}	
}
